import React, { useEffect, useState } from 'react';
import { Tabs, PullRefresh, List } from 'react-vant';
import './style.css';
import axios from '../../api/axios';
import { useNavigate } from 'react-router-dom';

interface Department {
  id: number;
  departmentName: string;
}

interface DiseaseCategory {
  id: number;
  name: string;
  description: string;
  pic: string;
}

interface Doctor {
  doctorId: number;
  doctorName: string;
  imagePic: string;
  jobTitle: string;
  inauguralHospital: string;
  praise: number;
  serverNum: number;
  servicePrice: number;
  praiseNum: number;
  badNum: number;
}

export default function City() {
  const [departments, setDepartments] = useState<Department[]>([]);
  const [diseases, setDiseases] = useState<DiseaseCategory[]>([]);
  const [doctors, setDoctors] = useState<Doctor[]>([]);
  const [activeIndex, setActiveIndex] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [finished, setFinished] = useState(false);
  const [page, setPage] = useState(1);

  const navigate = useNavigate();
  // 获取科室列表
  useEffect(() => {
    setIsLoading(true);
    axios.get('/share/knowledgeBase/v1/findDepartment')
      .then(res => {
        if (res.data.status === '0000') {
          setDepartments(res.data.result);
        }
      })
      .catch(console.error)
      .finally(() => setIsLoading(false));
  }, []);

  // 获取病症列表
  useEffect(() => {
    const deptId = departments[activeIndex]?.id;
    if (deptId && departments.length > 0) {
      setIsLoading(true);
      axios.get('/share/knowledgeBase/v1/findDiseaseCategory', {
        params: { departmentId: deptId }
      })
        .then(res => {
          if (res.data.status === '0000') {
            setDiseases(res.data.result);
          }
        })
        .catch(console.error)
        .finally(() => setIsLoading(false));
    }
  }, [activeIndex, departments]);

  // 获取医生列表
  const fetchDoctors = async (isRefresh = false) => {
    const deptId = departments[activeIndex]?.id;
    if (!deptId || departments.length === 0) return;

    try {
      const currentPage = isRefresh ? 1 : page;
      const response = await axios.get('/user/inquiry/v1/findDoctorList', {
        params: {
          deptId,
          condition: 1,
          page: currentPage,
          count: 5
        }
      });

      if (response.data.status === '0000') {
        const newDoctors = response.data.result;
        if (isRefresh) {
          setDoctors(newDoctors);
          setPage(1);
        } else {
          setDoctors(prev => [...prev, ...newDoctors]);
        }
        setFinished(newDoctors.length < 5);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchDoctors(true);
  }, [activeIndex, departments]);

  const onRefresh = async () => {
    setRefreshing(true);
    await fetchDoctors(true);
  };

  const onLoad = async () => {
    setLoading(true);
    setPage(prev => prev + 1);
    await fetchDoctors();
  };

  const handleTabChange = (index: number) => setActiveIndex(index);

  const handleDiseaseClick = (id: number) => {
    // 跳转到疾病详情页
    navigate(`/appointment/${id}`);
  };
  return (
    <div className="city-container">
      <header className="page-header">
        <h4>
          常见病症 
          <span className="more-link">
            <a href="">更多 </a>
          </span>
        </h4>
      </header>

      <Tabs
        className="custom-tabs"
        sticky
        offsetTop={60}
        onChange={(name, index) => handleTabChange(index)}
        active={activeIndex}
        swipeable
        titleActiveColor="#1989fa"
      >
        {departments.map(dept => (
          <Tabs.TabPane
            key={dept.id}
            title={dept.departmentName}
            badge={diseases.length || 0}
          >
            <PullRefresh
              onRefresh={onRefresh}
              disabled={isLoading}
            >
              {isLoading ? (
                <div className="loading-shimmer">加载中...</div>
              ) : diseases.length === 0 || doctors.length === 0 ? (
                <div className="empty-state">
                  <p>暂无该科室数据</p>
                  <img src="https://via.placeholder.com/200x150" alt="暂无数据" />
                </div>
              ) : (
                <div className="content">
                  <div className="doctor-section">
                    <h5 className="section-title">推荐医生</h5>
                    <div className="doctor-grid">
                      {doctors.map(doctor => (
                        <div key={doctor.doctorId} className="doctor-card">
                          <div className="doctor-avatar">
                            <img src={doctor.imagePic || "https://via.placeholder.com/80x80"} alt={doctor.doctorName} />
                          </div>
                          <div className="doctor-info">
                            <h6>{doctor.doctorName}</h6>
                            <p className="title">{doctor.jobTitle}</p>
                            <p className="hospital">{doctor.inauguralHospital}</p>
                            <div className="rating">
                              <span>好评率: {doctor.praise}</span>
                              <span>服务: {doctor.serverNum}人</span>
                              <span><button onClick={() => handleDiseaseClick(doctor.doctorId)}>咨询一下</button></span>
                            </div>
                            <div className="price">咨询价: {doctor.servicePrice} H币</div>
                          </div>
                        </div>
                      ))}
                    </div>
                    <div className="load-more-container">
                      {!finished && (
                        <p
                          className="load-more-btn"
                          onClick={onLoad}
                          disabled={loading}
                        >
                          {loading ? '加载中...' : '点击加载更多'}
                        </p>
                      )}
                      {finished && <div className="no-more">没有更多了</div>}
                    </div>
                  </div>
                </div>
              )}
            </PullRefresh>
          </Tabs.TabPane>
        ))}
      </Tabs>
    </div>
  );
}
